const INITIAL_STATE = {
  list: [],
  str: 0,
  carlist: JSON.parse(localStorage.getItem("carlist")) || [],
  zj: JSON.parse(localStorage.getItem("zj")) || 0,
  NewList: JSON.parse(localStorage.getItem("newlist")) || [],
};

let reducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case "GET_LIST":
      console.log(action);
      if (localStorage.getItem("list")) {
        localStorage.setItem("list", JSON.stringify("action.payload"));
      } else {
        return {
          ...state,
          list: [...action.payload],
        };
      }
    // eslint-disable-next-line no-fallthrough
    case "CHEC_KBOX":
      return {
        ...state,
        str: [...action.payload],
      };
    case "GET_CAR_LIST":
      return {
        ...state,
        carlist: [...action.payload],
      };
    // 加加方法
    case "ADD":
      state.carlist[action.payload].cont =
        state.carlist[action.payload].cont + 1;
      localStorage.setItem("carlist", JSON.stringify(state.carlist));
      return {
        ...state,
        carlist: [...state.carlist],
      };
    // 减减方法
    case "SUB":
      if (state.carlist[action.payload].cont > 0) {
        state.carlist[action.payload].cont =
          state.carlist[action.payload].cont - 1;
      } else {
        state.carlist[action.payload].cont = 0;
      }
      localStorage.setItem("carlist", JSON.stringify(state.carlist));

      return {
        ...state,
        carlist: [...state.carlist],
      };
    // 总价方法
    case "ZJQQ":
      let allNum = 0;
      // eslint-disable-next-line array-callback-return
      state.carlist.map((item) => {
        allNum += item.cont * item.price * 1;
      });
      localStorage.setItem("zj", JSON.stringify(allNum));
      return {
        ...state,
        zj: allNum,
      };
    // 加入购物车方法
    case "REMOVE":
      let itemList = state.NewList.findIndex(
        (item) => item.id === action.payload.id
      );
      if (itemList === -1) {
        state.NewList.push(action.payload);
      } else {
        console.log(66666);
        state.NewList[itemList].cont++;
      }
      localStorage.setItem("newlist", JSON.stringify(state.NewList));
      return {
        ...state,
        ...state.NewList,
      };
    default:
      return state;
  }
};
export default reducer;
